import CryptoJS from "crypto-js";
import './dist/index.umd'
import {ref} from "vue";

const recorder = new RecorderManager("/src/utils/iat/dist");
let APPID = "52eecca0";
let API_SECRET = "MGZiY2U0YThlNjY0YmFkZTRiNWJjOWU0";
let API_KEY = "7387430e9c93ed394045a07999fb4cbd";
let iatWS = {};
let countdownInterval = '';
let resultText = "";
let resultTextTemp = "";
export let textList = ref(null)
export let speechIng = ref(false)

export function connectWebSocket() {
    const websocketUrl = getWebSocketUrl();
    iatWS = new WebSocket(websocketUrl);
    iatWS.onopen = (e) => {
        // 开始录音
        recorder.start({
            sampleRate: 16000,
            frameSize: 1280,
        });
        let params = {
            common: {
                app_id: APPID,
            },
            business: {
                language: "zh_cn",
                domain: "iat",
                accent: "mandarin",
                vad_eos: 5000,
                dwa: "wpgs",
            },
            data: {
                status: 0,
                format: "audio/L16;rate=16000",
                encoding: "raw",
            },
        };
        iatWS.send(JSON.stringify(params));
    };
    iatWS.onmessage = (e) => {
        renderResult(e.data);
        console.log(e.data)
        // console.log(e.data);
    };
    iatWS.onerror = (e) => {
        console.error(e);
    };
    iatWS.onclose = (e) => {
        // console.error(e);
        speechIng.value = false
    };
}

function getWebSocketUrl() {
    // 请求地址根据语种不同变化
    let url = "wss://iat-api.xfyun.cn/v2/iat";
    let host = "iat-api.xfyun.cn";
    let apiKey = API_KEY;
    let apiSecret = API_SECRET;
    let date = new Date().toGMTString();
    let algorithm = "hmac-sha256";
    let headers = "host date request-line";
    let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`;
    let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    let signature = CryptoJS.enc.Base64.stringify(signatureSha);
    let authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    let authorization = btoa(authorizationOrigin);
    url = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
    return url;
}

recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
    if (iatWS.readyState === iatWS.OPEN) {
        speechIng.value = true
        iatWS.send(
            JSON.stringify({
                data: {
                    status: isLastFrame ? 2 : 1,
                    format: "audio/L16;rate=16000",
                    encoding: "raw",
                    audio: toBase64(frameBuffer),
                },
            })
        );
        if (isLastFrame) {
            countdown()
        }
    }
};

function toBase64(buffer) {
    let binary = "";
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}

export function countdown() {
    let seconds = 60;
    speechIng.value = false
  // textList.value = '';
    countdownInterval = setInterval(() => {
        seconds = seconds - 1;
        if (seconds <= 0) {
            clearInterval(countdownInterval);
            recorder.stop();
        }
    }, 1000);
}

function renderResult(resultData) {
    // 识别结束
    let jsonData = JSON.parse(resultData);
    if (jsonData.data && jsonData.data.result) {
        let data = jsonData.data.result;
        let str = "";
        let ws = data.ws;
        for (let i = 0; i < ws.length; i++) {
            str = str + ws[i].cw[0].w;
        }
        // 开启wpgs会有此字段(前提：在控制台开通动态修正功能)
        // 取值为 "apd"时表示该片结果是追加到前面的最终结果；取值为"rpl" 时表示替换前面的部分结果，替换范围为rg字段
        if (data.pgs) {
            if (data.pgs === "apd") {
                // 将resultTextTemp同步给resultText
                resultText = resultTextTemp;
            }
            // 将结果存储在resultTextTemp中
            // resultTextTemp = resultText + str;
        } else {
            resultText = resultText + str;
        }
        textList.value = resultTextTemp || resultText || "";
    }
    if (jsonData.code === 0 && jsonData.data.status === 2) {
        iatWS.close();
    }
    if (jsonData.code !== 0) {
        iatWS.close();
        console.error(jsonData);
    }
}

